﻿using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore;
using Abp.Extensions;
using Microsoft.EntityFrameworkCore;

namespace pandx.Mulan.EntityFrameworkCore;

public class DatabaseCheckHelper:ITransientDependency
{
    private readonly IDbContextProvider<MulanDbContext> _dbContextProvider;
    private readonly IUnitOfWorkManager _unitOfWorkManager;

    public DatabaseCheckHelper(IDbContextProvider<MulanDbContext> dbContextProvider, IUnitOfWorkManager unitOfWorkManager)
    {
        _dbContextProvider = dbContextProvider;
        _unitOfWorkManager = unitOfWorkManager;
    }

    public bool Exist(string connectionString)
    {
        if (connectionString.IsNullOrEmpty())
        {
            return false;
        }

        try
        {
            using (var uow = _unitOfWorkManager.Begin())
            {
                using (_unitOfWorkManager.Current.SetTenantId(null))
                {
                    _dbContextProvider.GetDbContext().Database.OpenConnection();
                    uow.Complete();
                }
            }
        }
        catch
        {
            return false;
        }

        return true;
    }
}